<template>
  <div class="rolesBox">
    <!-- <h1>User组件</h1> -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row type="flex">
        <el-col :span="8">
          <el-row type="flex">
            <el-col :span="20">
              <el-button type="primary" @click="dialogFormVisibleAdd = true"
                >添加角色</el-button
              >
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-table v-loading = "isLoading" :data="tableData" border style="width: 100%">
        <el-table-column type="expand" class="menu">
          <template slot-scope="scope">
            <el-row
              class="menuList"
              v-for="firstChildren in scope.row.children"
              :key="firstChildren.id"
            >
              <el-col :span="4" align="center">
                <el-tag
                  closable
                  @close="deleteRight(scope.row, firstChildren.id)"
                  effect="dark"
                  >{{ firstChildren.authName }}</el-tag
                >
                <i
                  class="el-icon-caret-right"
                  v-if="firstChildren.children.length !== 0"
                ></i>
              </el-col>
              <el-col :span="20" class="rightMenu">
                <el-row
                  v-for="secondChildren in firstChildren.children"
                  :key="secondChildren.id"
                >
                  <el-col :span="4">
                    <el-tag
                      closable
                      @close="deleteRight(scope.row, secondChildren.id)"
                      type="success"
                      effect="dark"
                      >{{ secondChildren.authName }}</el-tag
                    >
                    <i
                      class="el-icon-caret-right"
                      v-if="secondChildren.children.length !== 0"
                    ></i>
                  </el-col>
                  <el-col :span="20">
                    <el-tag
                      closable
                      @close="deleteRight(scope.row, thirdChildren.id)"
                      type="warning"
                      v-for="thirdChildren in secondChildren.children"
                      :key="thirdChildren.id"
                      effect="dark"
                    >
                      {{ thirdChildren.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-row v-if="scope.row.children.length === 0">
              <el-col :span="24">该角色没有分配权限，请前往分配！</el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          width=""
        ></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="">
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-setting"
              @click="showTree(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="dialogFormVisibleAdd">
      <el-form :model="currentAdd" :rules="rules" ref="formAdd">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="currentAdd.roleName" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input v-model="currentAdd.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd">取 消</el-button>
        <el-button type="primary" @click="AddRoles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改角色 -->
    <el-dialog title="修改角色" :visible.sync="dialogFormVisibleEdit">
      <el-form :model="currentEdit" :rules="rules" ref="formEdit">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="currentEdit.roleName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="角色描述"
          prop="roleDesc"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="currentEdit.roleDesc"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 授权角色树 -->
    <el-dialog title="授权角色" :visible.sync="dialogFormVisibleTree">
      <div class="tree-container">
        <el-tree
          :data="rightList"
          show-checkbox
          ref="tree"
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="selectedRights"
          :props="defaultProps"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleTree = false">取 消</el-button>
        <el-button type="primary" @click="confirmRoleRight">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  getRoleList,
  getRolesInfo,
  getAddRoles,
  getEditRoles,
  getDeleteRoles,
  getRightList,
  getConfirmRoleRight,
  getDeleteRoleRight,
} from "../../api/index";
export default {
  data() {
    return {
      isLoading: true,
      tableData: [],
      currentAdd: {},
      currentEdit: {},
      dialogFormVisibleEdit: false,
      dialogFormVisibleAdd: false,
      formLabelWidth: "120px",

      dialogFormVisibleTree: false,
      currentRole: {},
      rightList: [],
      defaultProps: {
        children: "children", // // 树形组件展示的数据源
        label: "authName", // 树形组件显示的标题字段
      },
      // 默认打开已选中的权限
      selectedRights: [],

      // 验证规则
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 8,
            message: "长度在 2 到 8 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getRoles();
  },
  methods: {
    async getRoles() {
      let {
        data,
        meta: { msg, status },
      } = await getRoleList(this.params);
      this.isLoading = false;
      this.tableData = data;
      // console.log(data);
    },

    // 添加角色
    async AddRoles() {
      let result = await this.$refs["formAdd"].validate().catch(() => {});
      console.log(result);
      if (!result) return false;
      let res = await getAddRoles(this.currentAdd);
      let {
        meta: { msg, status },
      } = res;

      if (status == 201) {
        this.$message.success(msg);
        this.dialogFormVisibleAdd = false;
        this.getRoles();
      } else {
        this.$message.warning(msg);
      }
    },
    // 取消添加
    cancelAdd() {
      this.dialogFormVisibleAdd = false;
    },
    // 修改
    async handleEdit(row) {
      this.dialogFormVisibleEdit = true;
      // 根据 角色ID 查询角色
      let res = await getRolesInfo(row.id);
      let { data } = res;
      this.currentEdit = data;
    },
    // 确认修改
    async editRoles() {
      let result = await this.$refs["formEdit"].validate().catch(() => {});
      console.log(result);
      if (!result) return false;

      let res = await getEditRoles(this.currentEdit);
      console.log(res);
      let {
        meta: { msg, status },
      } = res;

      if (status == 200) {
        this.$message.success("修改成功");
        this.dialogFormVisibleEdit = false;
        this.getRoles();
      } else {
        this.$message.warning("修改失败");
      }
    },
    // 取消修改
    cancelEdit() {
      this.dialogFormVisibleEdit = false;
    },

    // 删除
    async handleDelete(row) {
      try {
        let res = await this.$confirm("是否删除该角色？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // console.log(res)
        if (res == "confirm") {
          // this.$message.success("成功删除用户");
          let res = await getDeleteRoles(row.id);
          let {
            meta: { msg, status },
          } = res;
          if (status == 200) {
            this.$message.success(msg);
            this.getRoles();
          } else {
            this.$message.warning(msg);
          }
        }
      } catch {
        this.$message.info("取消删除");
      }
    },
    // 显示设置权限树
    async showTree(row) {
      this.dialogFormVisibleTree = true;
      this.currentRole = row; //当前角色权限
      let res = await getRightList({ type: "tree" });
      let {
        data,
        meta: { msg, status },
      } = res;
      if (status == 200) {
        // console.log(data);
        this.rightList = data;

        // 默认打开已选中的权限 selectedRights
        this.selectedRights.length = 0;
        // 遍历已选中的权限 把权限id 取出来 存在selectedRights中
        //递归
        this.checkNodeId(this.currentRole,this.selectedRights)
      } else {
        this.$message.error(msg);
      }
    },
    checkNodeId(currentItem,selectedArr){
        if(!currentItem.children){
          return selectedArr.push(currentItem.id)
        }
        currentItem.children.forEach(item => {
          return this.checkNodeId(item,selectedArr)
        })
        
    },

    // 删除权限
    async deleteRight(row, rightId) {
      try {
        let result = await this.$confirm("是否删除该权限？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        // console.log(res)
        if (result == "confirm") {
          // this.$message.success("成功删除用户");
          // 角色id  权限id
          let res = await getDeleteRoleRight({
            roleId: row.id,
            rightId: rightId,
          });
          // console.log(res)
          let {
            data,
            meta: { status, msg },
          } = res;
          if (status == 200) {
            row.children = data;
            this.$message.success(msg);
          } else {
            this.$message.error(msg);
          }
        }
      } catch {
        this.$message.info("取消删除");
      }
    },

    async confirmRoleRight() {
      // // 获取到所有选中的权限ID
      let rids = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ].join(",");

      //  参数：当前角色id  被选中的权限id列表
      let roleId = this.currentRole.id;
      let res = await getConfirmRoleRight(roleId, { rids: rids });
      if (res.meta.status == 200) {
        this.$message.success("分配权限成功");
        this.dialogFormVisibleTree = false;
        this.getRoles();
      } else {
        this.$message.error(res.meta.msg);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  background-color: initial;
  font-size: 12px;
  line-height: initial;
  height: initial;
  padding: 0px;
}
.el-card__body {
  min-width: 400px;
}

.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}

.menuList {
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #efefef;
  border-left: 1px solid #efefef;
  border-right: 1px solid #efefef;
  margin: 0 50px;
  &:nth-last-of-type(1) {
    border-bottom: 1px solid #efefef;
  }
  .rightMenu {
    border-left: 1px solid #efefef;
    padding-left: 50px;
  }
  .el-tag {
    margin: 10px 5px 5px 0px;
    // margin-right: 5px;
    // margin-bottom: 5px;
  }
}

.tree-container {
  height: 500px;
  overflow: auto;
}
</style>

